using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Log2SQL
{
    public partial class MainForm : Form
    {
        private LogImport _importer;

        public MainForm()
        {
            InitializeComponent();
        }

        private void rbSQLAuth_CheckedChanged(object sender, EventArgs e)
        {
            lblUsername.Enabled = rbSQLAuth.Checked;
            lblPsw.Enabled = rbSQLAuth.Checked;
            txUsername.Enabled = rbSQLAuth.Checked;
            txPsw.Enabled = rbSQLAuth.Checked;
        }

        private void btnAddFile_Click(object sender, EventArgs e)
        {
            if (logsOpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                foreach (string filename in logsOpenFileDialog.FileNames)
                {
                    if(!ListItemExists(filename))
                        lstFiles.Items.Add(filename);
                }
            }
        }

        private void btnRemoveFile_Click(object sender, EventArgs e)
        {
            for (int i = lstFiles.SelectedItems.Count - 1; i >= 0; i--)
            {
                lstFiles.Items.Remove(lstFiles.SelectedItems[i]);
            }
        }

        private void btnGetDatabases_Click(object sender, EventArgs e)
        {
            //list available db's
            string server = txServer.Text.Trim();
            Cursor.Current = Cursors.WaitCursor;
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = "data source=" + server + ";initial catalog=master;Integrated Security=SSPI;Connection Timeout=5";
            try
            {
                cn.Open();
                cn.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Could not connect to server " + server + "\r\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor.Current = Cursors.Default;
                return;
            }

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            cn.Open();
            cmd.CommandText = "SELECT name FROM sysdatabases";
            try
            {
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    cmbDatabase.Items.Clear();
                    while (dr.Read())
                    {
                        cmbDatabase.Items.Add(dr["Name"]);
                    }
                    cmbDatabase.SelectedIndex = 0;
                }
                dr.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error getting the list of databases from server " + server + "\r\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor.Current = Cursors.Default;
                return;
            }
            cn.Close();
            Cursor.Current = Cursors.Default;
        }

        private void btnGetServers_Click(object sender, EventArgs e)
        {
            //get servers nearby
            HDCustomAction.SqlBrowserForm frm = new HDCustomAction.SqlBrowserForm();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                txServer.Text = frm.SQLServer;
            }
        }

        private void wpLogFiles_CloseFromNext(object sender, Gui.Wizard.PageEventArgs e)
        {
            //check if files specified
            if (lstFiles.Items.Count == 0)
            {
                MessageBox.Show(this, "Please specify one or more log files to import", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                e.Page = wpLogFiles;
            }
        }

        private void wpSQLServer_CloseFromNext(object sender, Gui.Wizard.PageEventArgs e)
        {
            //check if sqlserver specified
            if (txServer.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please specify SQL server name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                e.Page = wpSQLServer;
            }
        }

        private void wpDatabase_CloseFromNext(object sender, Gui.Wizard.PageEventArgs e)
        {
            //check if db specified
            if (cmbDatabase.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please specify database name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                e.Page = wpDatabase;
            }
        }

        private void wpDatabase_Show(object sender, EventArgs e)
        {
            btnGetDatabases.Text = "&list databases from \"" + txServer.Text.Trim() + "\"";
        }

        private void wpAuthentication_CloseFromNext(object sender, Gui.Wizard.PageEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to start the import process?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                e.Page = wpAuthentication;
            }
        }

        private void wpProgress_ShowFromNext(object sender, EventArgs e)
        {
            wizard1.BackEnabled = false;
            wizard1.NextEnabled = false;
            wizard1.CancelEnabled = false;
            btnAbort.Enabled = true;

            //start import
            Cursor.Current = Cursors.WaitCursor;
            if (rbW3C.Checked)
                _importer = new W3CLogImport();
            else
                _importer = new NCSALogImport();

            _importer.DatabaseName = cmbDatabase.Text.Trim();
            _importer.DesiredTableName = txTableName.Text.Trim();
            _importer.SQLServerName = txServer.Text.Trim();
            _importer.PutAllInOneTable = rbOneTable.Checked;
            
            _importer.LogImportMode = rbImportDataSQL.Checked ? ImportMode.SQLImport :
                (rbImportDataMDB.Checked ? ImportMode.MDBImport : ImportMode.GenerateScript);
            
            _importer.SQLScriptPath = txScriptPath.Text.Trim();
            _importer.MDBFilePath = txMDBPath.Text.Trim();

            if (_importer.LogImportMode == ImportMode.SQLImport)
            {
                if (rbSQLAuth.Checked)
                {
                    _importer.SQLAuthMode = SQLServerAuthMode.SQLAuthentication;
                    _importer.SQLUserName = txUsername.Text.Trim();
                    _importer.SQLPassword = txPsw.Text.Trim();
                }
                else
                {
                    _importer.SQLAuthMode = SQLServerAuthMode.WindowsAuthentication;
                }
            }

            string[] files = new string[lstFiles.Items.Count];
            int i = 0;
            foreach (object itm in lstFiles.Items)
            {
                files[i] = itm.ToString();
                i++;
            }
            _importer.UpdateCurrFileProgress = new W3CLogImport.UpdateCurrFileProgressDelegate(UpdateCurrFileProgress);
            _importer.UpdateOverallProgress = new W3CLogImport.UpdateOverallProgressDelegate(UpdateOverallProgress);
            int resCount = _importer.Import(files);
            Cursor.Current = Cursors.Default;
            wizard1.NextEnabled = true;

            lblResult.Text = string.Format("Imported {0} rows.", resCount);
            lblResult.Visible = true;
            btnStartover.Enabled = true;
            btnAbort.Enabled = false;
        }

        public void UpdateCurrFileProgress(byte progressValue)
        {
            pbCurr.Value = progressValue;
        }
        public void UpdateOverallProgress(byte progressValue)
        {
            pbOverall.Value = progressValue;
        }

        private void wpTable_CloseFromNext(object sender, Gui.Wizard.PageEventArgs e)
        {
            //check if tablename specified
            if (txTableName.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please specify table name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                e.Page = wpTable;
            }
        }

        //checks if an item exists in the list
        private bool ListItemExists(string itemText)
        {
            foreach (object item in lstFiles.Items)
            {
                if (item.ToString().Equals(itemText)) return true;
            }
            return false;
        }

        private void wpImportMode_CloseFromNext(object sender, Gui.Wizard.PageEventArgs e)
        {
            if (rbImportDataSQL.Checked) return;

            if (rbGenerateScript.Checked)
            {
                //check if sqlscriptpath specified
                if (txScriptPath.Text.Trim().Length == 0)
                {
                    MessageBox.Show("Please specify script filename", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    e.Page = wpImportMode;
                    return;
                }
            }
            else if (rbImportDataMDB.Checked)
            {
                //check if mdb-path specified
                if (txMDBPath.Text.Trim().Length == 0)
                {
                    MessageBox.Show("Please specify .MDB filename", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    e.Page = wpImportMode;
                    return;
                }
            }

            if (MessageBox.Show("Are you sure you want to start the import process?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                e.Page = wpImportMode;
            else
                e.Page = wpProgress;
        }

        private void rbGenerateScript_CheckedChanged(object sender, EventArgs e)
        {
            txScriptPath.Enabled = rbGenerateScript.Checked;
            lblScriptPath.Enabled = rbGenerateScript.Checked;
            btnBrowseScript.Enabled = rbGenerateScript.Checked;
        }

        private void btnBrowseScript_Click(object sender, EventArgs e)
        {
            if (sqlscriptSaveFileDialog.ShowDialog() == DialogResult.OK && sqlscriptSaveFileDialog.FileName!="")
            {
                txScriptPath.Text = sqlscriptSaveFileDialog.FileName;
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm frm = new AboutForm();
            frm.ShowDialog();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnStartover_Click(object sender, EventArgs e)
        {
            //start over
            lblResult.Visible = false;
            btnStartover.Enabled = false;
            lstFiles.Items.Clear();
            wizard1.PageIndex = 0;
            txTableName.Text = string.Empty;
        }

        private void btnAbort_Click(object sender, EventArgs e)
        {
            if (_importer != null)
            {
                _importer.Abort();
                btnAbort.Enabled = false;
            }
        }

        private void btnBrowseMDB_Click(object sender, EventArgs e)
        {
            if (mdbOpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                txMDBPath.Text = mdbOpenFileDialog.FileName;
            }
        }

        private void rbImportDataMDB_CheckedChanged(object sender, EventArgs e)
        {
            txMDBPath.Enabled = rbImportDataMDB.Checked;
            lblMDBPath.Enabled = rbImportDataMDB.Checked;
            btnBrowseMDB.Enabled = rbImportDataMDB.Checked;
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}